package com.weiyuwqj.app.web;

import com.weiyuwqj.api.util.IpUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SimpleCORSFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    String key="NWE2NTg4YzQtZTVmNy00NWVmLTlkOTAtMmJkYjhiNWIwY2Jl";
    String userKey="RskqNRL0WSwwVYFbGWfu54/wNPdD0I1N9u+e1PbTZO3zbk/LV95JvePbewf4QPYmqJ9WG9zpLXvZ" +
            "kgK3nf4eXw==MGVlOWQzZWUtZGRkYy00YTNkLTgzZjEtNTgyNWVmZWFmNDk0";

    HttpServletRequest request=(HttpServletRequest)req;
    IpUtils.set(request);

    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers","x-requested-with, x-access-token,x-user-token");

   String path=request.getServletPath();

  /*if(path.startsWith("/mobile")){
      String info="";
      if(!path.equals("/mobile/appToken")){
        String token = request.getHeader("x-access-token");
        if(token!=null){
          try{
            info= JwtUtils.verify(token, key);
          }catch (Exception e){
            e.printStackTrace();
          }
        }
        if(info==null||info.isEmpty()){
          response.setContentType("application/json;charset=UTF-8");
          response.setHeader("Pragma", "No-cache");
          response.setHeader("Cache-Control", "no-cache");
          response.setDateHeader("Expires", 0);
          response.setStatus(401);
          PrintWriter out =response.getWriter();
          ObjectMapper mapper=new ObjectMapper();
          HashMap<String,Object> msg=new HashMap<String,Object>();
          msg.put("result","fail");
          msg.put("messageCode","sys.sessionTimeout");
          String json=mapper.writeValueAsString(msg);
          out.print(json);
          out.flush();
          out.close();
          return;
        }

      }

      String[] needPath={"/mobile/user","/mobile/account","/mobile/coupon","/mobile/invest","/mobile/invite","/mobile/ticket","/mobile/gold","/mobile/redeemCode","/mobile/item/buy","/mobile/lottery","/mobile/modifyStatus"};
      String[] noNeedPath={"/mobile/user/doLoginSendSms","/mobile/user/registerSendSms","/mobile/user/backPasswordSms","/mobile/user/loginBandingSms"};
      boolean isMath = false;
      if(isMatch(path,needPath)){
        isMath =true;
      }
      if(isMatch(path,noNeedPath)){
        isMath =false;
      }
      if(isMath){
        String userToken = request.getHeader("x-user-token");
        String userInfo = "";
        if(userToken != null){
          try{
            userInfo= JwtUtils.verify(userToken, userKey);
          }catch (Exception e){
            e.printStackTrace();
          }
        }
        if(userInfo==null||userInfo.isEmpty()){
          response.setContentType("application/json;charset=UTF-8");
          response.setHeader("Pragma", "No-cache");
          response.setHeader("Cache-Control", "no-cache");
          response.setDateHeader("Expires", 0);
          response.setStatus(401);
          PrintWriter out =response.getWriter();
          ObjectMapper mapper=new ObjectMapper();
          HashMap<String,Object> msg=new HashMap<String,Object>();
          msg.put("result","fail");
          msg.put("messageCode","sys.sessionTimeout");
          String json=mapper.writeValueAsString(msg);
          out.print(json);
          out.flush();
          out.close();
          return;
        }
      }
    }*/
    chain.doFilter(req, res);
    IpUtils.clear();
  }
  private boolean isMatch(String path,String[] paths){
    boolean isMatch=false;
    for(String p:paths){
      if(path.startsWith(p)){
        isMatch=true;
        break;
      }
    }
    return isMatch;
  }

  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}